import aiomysql
import asyncio


# 一个游标对象无法在多个task任务并发读写
async def connect_sql():
    con = await aiomysql.connect(user='root', password='888888', db='test')
    cursor = await con.cursor()

    await cursor.execute('select * from tx_works;')
    res = await cursor.fetchall()
    print(res)


    await cursor.close()
    con.close()


# 建议使用下面这种方法
async def connect_sql_many():
    #连接池
    pool = await aiomysql.create_pool(user='root', password='888888', db='test')

    # 上下文管理器自动关闭对象
    async with pool.acquire() as con:
        async with con.cursor() as cursor:
            await cursor.execute('select * from tx_works;')
            res = await cursor.fetchall()
            print(res)



# asyncio.run(connect_sql())
asyncio.run(connect_sql_many())
